package com.ag.improvedjava.iterable;

import java.util.Iterator;
import java.util.NoSuchElementException;

final class ElementAt<T> {

	private final Iterable<T> iterable;
	private final int index;

	ElementAt(Iterable<T> iterable, int index) {
		this.iterable = iterable;
		this.index = index;
	}

	T value() {
		if (index < 0) {
			throw new IndexOutOfBoundsException(
					"The index can not be negative.");
		}
		T next = null;
		Iterator<T> it = iterable.iterator();
		try {
			for (int i = -1; i < index; i++) {
				next = it.next();
			}
		} catch (NoSuchElementException e) {
			throw new IndexOutOfBoundsException("The index is too large.");
		}
		return next;
	}
}